//
//  WmcEditPhotoVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/15.
//

import UIKit
import YPBedrock

// MARK: - 扩展WmcEditPhotoVC + WmcNavigatorProtocol

extension WmcEditPhotoVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.editPhoto]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcEditPhotoVM()
        if let viewModel = parms.context as? WmcEditPhotoVM {
            vm = viewModel
        }
        let vc = WmcEditPhotoVC(vm)
        vc.preView.image = vm.inputImage
        return vc
    }
}

// MARK: - 扩展WmcEditPhotoVC + WmcVMProtocol

extension WmcEditPhotoVC: WmcVMProtocol {
    typealias VMType = WmcEditPhotoVM
}

// MARK: - [WmcEditPhotoVC]

class WmcEditPhotoVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // Internal

    static var TooBarHeight: CGFloat { Wmc_safeAreaBottom + 65 }

    lazy var preView: WmcEditPhotoPreviewView = {
        let view = WmcEditPhotoPreviewView()

        return view
    }()

    lazy var toolView: WmcEditPhotoToolView = {
        let view = WmcEditPhotoToolView()
        return view
    }()

    lazy var saveBtn: UIButton = {
        let btn = UIButton.Wmc_themeColorBtn(color: .wmc_mainTheme, title: "保存")
        return btn
    }()

    lazy var completeView: WmcEditPhotoCompleteView = {
        let view = WmcEditPhotoCompleteView()
        return view
    }()

    /// 编辑的照片
    var editImage: UIImage = .init()
    /// 当前正在编辑的标签
    var currentEditTagView: WmcBaseTagView?

    override func makeUI() {
        view.backgroundColor = .black

        makeNavView(style: .dark)
        title = "返回"

        navView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-6)
            make.width.equalTo(52.wmc_autoHor)
            make.height.equalTo(32)
            make.right.equalTo(-Wmc_standardEdge.right)
        }

        addSubview(toolView)
        toolView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(Self.TooBarHeight)
        }

        addSubview(preView)
        preView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(toolView.snp.top)
        }
    }

    override func backAction() {
        popVC(style: .bottom)
    }

    override func bindViewAction() {
        // 点击保存
        saveBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.saveBtn.isUserInteractionEnabled = false
            WmcHudManager.toast("正在保存")
            weakSelf.preView.cancelAllTagEdit() // 取消所有编辑状态

            var tagImage: UIImage?
            let size = weakSelf.preView.tagTintView.frame.size
            guard size.width > 0 && size.height > 0 else {
                return
            }
            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
            guard let ctx = UIGraphicsGetCurrentContext() else { return }
            weakSelf.preView.tagTintView.layer.render(in: ctx)
            tagImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            guard let tagImage = tagImage else {
                WmcHudManager.toast("保存失败")
                weakSelf.saveBtn.isUserInteractionEnabled = true
                return
            }
            // 处理图片
            weakSelf.viewModel.disposeImage(weakSelf.preView.image!,
                                            tagImage: tagImage) { [weak self] image in
                guard let weakSelf = self else { return }
                weakSelf.viewModel.saveImage(image)
            }
        }

        // 保存下的操作
        // -- 上传
        completeView.uploadBtn.yp.addEvent { _ in
        }

        // -- 分享微信
        completeView.wechatFriendBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.shareWechat()
        }

        // -- 微信朋友圈
        completeView.wechatCycleBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.shareFirendCircle()
        }

        // -- 完成
        completeView.completeBtn.yp.addEvent { _ in
            YPApp.CurrentVC?.dismiss(animated: true, completion: { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.backAction()
            })
        }

        // 点击添加水印
        toolView.addTextRemarkBtn.yp.addEvent { _ in
        }

        // 点击加字备注
        toolView.addTextRemarkBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            let vc = WmcCreateTagVC(mode: .add)
            vc.modalPresentationStyle = .overFullScreen
            weakSelf.present(vc, animated: true, completion: nil)
            vc.outputTageViewBlock = { [weak self] tagView in
                guard let weakSelf = self else { return }
                tagView.frame = CGRect(origin: tagView.frame.origin, size: tagView.defaultSize)
                weakSelf.preView.addTag(tagView)
            }
        }

        // 编辑标签
        preView.editTagBlock = { [weak self] tagView in
            guard let weakSelf = self else { return }
            weakSelf.currentEditTagView = tagView

            let vc = WmcCreateTagVC(mode: .edit(tagView: tagView))
            vc.modalPresentationStyle = .overFullScreen
            weakSelf.present(vc, animated: true, completion: nil)
            vc.outputTageViewBlock = { [weak self] tagView in
                guard let weakSelf = self else { return }
                // 编辑前的显示参数赋值
                if let currentEditTagView = weakSelf.currentEditTagView {
                    // 还原位置和新大小
                    tagView.frame = CGRect(origin: tagView.frame.origin, size: tagView.defaultSize)
                    tagView.center = currentEditTagView.center
                    // 还原缩放和大小
                    var transform = CGAffineTransform.YP.CreateScale(currentEditTagView.currentScale)
                    transform = transform.rotated(by: currentEditTagView.currentAngle)
                    tagView.transform = transform
                    tagView.recoreCurrentTransform()
                    tagView.moveFromImageViewToBack()
                }
                // 狸猫换太子
                weakSelf.currentEditTagView?.removeFromSuperview()
                weakSelf.preView.addTag(tagView, isSightCenter: false, isAutoScale: false)
            }
            vc.deleteTageViewBlock = {
                weakSelf.currentEditTagView?.close()
            }
        }
    }

    override func bindViewModel() {
        // 保存完成回调
        viewModel.saveSubject.subscribe(onNext: { [weak self] image in
            guard let weakSelf = self else { return }
            weakSelf.saveBtn.isUserInteractionEnabled = true
            WmcHudManager.toast("保存成功")
            let presentVC = WmcPresentVC(config: .init(style: .sheet(),
                                                       contentView: weakSelf.completeView,
                                                       contentLayoutBlock: { make in
                                                           make.left.right.bottom.equalToSuperview()
                                                           make.height.equalTo(Wmc_safeAreaBottom + 220)
                                                       }))
            weakSelf.completeView.presentVC = presentVC // 用于返回弹窗
            presentVC.show()
        }).disposed(by: rx.disposeBag)
    }
}
